package cn.fl.audit.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.audit.service.IAudRejectOpinionService;
import cn.fl.audit.transform.AudRejOpnPageVOTransform;
import cn.fl.audit.vo.AudRejectOpinionPageVO;
import cn.fl.audit.vo.AudRejectOpinionVO;
import cn.fl.audit.vo.AudStandingBookVO;
import cn.fl.flow.service.ISysFlowRejRsnService;
import cn.fl.flow.vo.SysFlowRejRsnVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.preloan.IAuditRejectOpinionService;
import cn.fl.preloan.condition.AuditRejectOpQueryCondition;
import cn.fl.preloan.dto.audit.AuditRejectOpinionDTO;
import cn.fl.preloan.dto.audit.AuditStandingBookDTO;
import cn.fl.preloan.dto.audit.BatchAddAudRejectOpRequest;
import cn.fl.preloan.dto.audit.BatchAddNullAudRejectOpRequest;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.fl.commons.result.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 驳回意见 控制层
 */
@Controller
@RequestMapping("/audit/audRejectOpinion")
public class AudRejectOpinionController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(AudRejectOpinionController.class);

	/**
	 * AudRejectOpinion 服务层BEAN
	 */
	@Autowired
	private IAudRejectOpinionService audRejectOpinionService;
	
	/**
	 * 流程审核驳回意见服务
	 */
	@Autowired
	private ISysFlowRejRsnService sysFlowRejRsnService;

	@Autowired
	private IAuditRejectOpinionService auditRejectOpinionService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("audit/audRejectOpinion/list");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到新增/修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		String projectId = request.getParameter("projectId");//项目ID
		String capPayId = request.getParameter("capPayId");//付款信息ID
		String proIntId = request.getParameter("proIntId");//流程ID
		String taskId = request.getParameter("taskId");//任务ID
		String taskDefKey = request.getParameter("taskDefKey");//任务定义KEY
		String taskNm = request.getParameter("taskNm");//任务定义名称
		//驳回意见类型
		String opinionTypeCd = request.getParameter("opinionTypeCd");//任务定义KEY
		//台账类型
		String bookTypCd = request.getParameter("bookTypCd");//任务定义KEY
		ModelAndView view = new ModelAndView("audit/audRejectOpinion/audRejectOpinionAdd");
		view.addObject("projectId", projectId);
		view.addObject("proIntId", proIntId);
		view.addObject("taskId", taskId);
		view.addObject("taskDefKey", taskDefKey);
		view.addObject("taskNm", taskNm);
		view.addObject("capPayId", capPayId);
		view.addObject("opinionTypeCd", opinionTypeCd);
		view.addObject("bookTypCd", bookTypCd);
		return view;
	}
	
	/**
	 * 获取驳回意见下拉数据
	 */
	@RequestMapping(value = "/getRejOpnJSON.do", method = { RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Object getRejOpnJSON(HttpServletRequest request, HttpServletResponse response){
		String pid = request.getParameter("pid");
		String rsnTypCd = request.getParameter("rsnTypCd");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(pid) || StringUtils.isEmpty(rsnTypCd)){
			BaseLogUtils.error(logger, "getRejOpnJSON", "获取数据,缺少参数.[pid="+pid+",rsnTypCd="+rsnTypCd+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		List<SysFlowRejRsnVO> sysFlowRejRsnList = new ArrayList<SysFlowRejRsnVO>();
		try{
			sysFlowRejRsnList = this.sysFlowRejRsnService.seachSysFlowRejRsnList(Long.valueOf(pid), rsnTypCd);
			result.setData(JSONObject.toJSON(sysFlowRejRsnList));
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getRejOpnJSON", "获取失败.[pid="+pid+",rsnTypCd="+rsnTypCd+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getRejOpnJSON", "获取失败.[pid="+pid+",rsnTypCd="+rsnTypCd+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		
		return result;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String proIntId = request.getParameter("proIntId");//流程ID
		String bookTypCd = request.getParameter("bookTypCd");//台账类型
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		AuditRejectOpQueryCondition qc = new AuditRejectOpQueryCondition();
		if(StringUtils.isNotEmpty(proIntId)){
			qc.setProIntId(proIntId);
		}
		if(StringUtils.isNotEmpty(bookTypCd)){
			qc.setBookTypCd(bookTypCd);
		}
		page.setCondition(qc);

		Pager pager = this.audRejectOpinionService.searchListPage(page);
		List<AudRejectOpinionPageVO> list = (List<AudRejectOpinionPageVO>) pager.getResultList();
		
		ListPageVO<AudRejectOpinionPageVO> listPage = new ListPageVO<AudRejectOpinionPageVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.audRejectOpinionService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			AudRejectOpinionVO vo = this.audRejectOpinionService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		List<AudRejectOpinionVO> VOList = new ArrayList<AudRejectOpinionVO>();
		String bookTypCd = request.getParameter("bookTypCd");
		try {
			VOList = this.getRequestParamForAdd(request);
			String resultCode;
			if(CollectionUtils.isNotEmpty(VOList)){
				List<AuditRejectOpinionDTO> dtoList = new ArrayList<>();
				for (AudRejectOpinionVO audRejectOpinionVO : VOList) {
					AuditRejectOpinionDTO auditRejectOpinionDTO = new AuditRejectOpinionDTO();
					BeanUtils.copyProperties(audRejectOpinionVO, auditRejectOpinionDTO);
					auditRejectOpinionDTO.setPayId(audRejectOpinionVO.getCapPayId());
					dtoList.add(auditRejectOpinionDTO);
				}
				BatchAddAudRejectOpRequest addRequest = new BatchAddAudRejectOpRequest(dtoList, bookTypCd, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
				ResponseData responseData = auditRejectOpinionService.batchAdd(addRequest);
				resultCode = responseData.getCode();
			}else{
				//TODO 驳回意见为空 点击保存 : 无台账生成台账 有台账删除意见
				String projectId = request.getParameter("projectId");//项目ID
				String capPayId = request.getParameter("capPayId");//付款信息ID
				String proIntId = request.getParameter("proIntId");//流程ID
				String taskId = request.getParameter("taskId");//任务ID
				String taskDefKey = request.getParameter("taskDefKey");//任务定义KEY
				String taskNm = request.getParameter("taskNm");//任务定义KEY
				AudStandingBookVO bookVO = new AudStandingBookVO();
				if(StringUtils.isNotEmpty(projectId)){
					bookVO.setProjectId(Long.valueOf(projectId));
				}
				if(StringUtils.isNotEmpty(capPayId)){
					bookVO.setPayId(Long.valueOf(capPayId));
				}
				bookVO.setProIntId(proIntId);
				bookVO.setTaskId(taskId);
				bookVO.setTaskDefKey(taskDefKey);
				bookVO.setTaskName(taskNm);
				bookVO.setCrtTm(new Date());
				bookVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());

				AuditStandingBookDTO auditStandingBookDTO = new AuditStandingBookDTO();
				BeanUtils.copyProperties(bookVO, auditStandingBookDTO);
				BatchAddNullAudRejectOpRequest addNullRequest = new BatchAddNullAudRejectOpRequest(auditStandingBookDTO, bookTypCd, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
				ResponseData responseData = auditRejectOpinionService.batchAddNull(addNullRequest);
				resultCode = responseData.getCode();
			}
			if (!ResponseData.SUCCESS_CODE.equals(resultCode)) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
				BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(VOList), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "add", "新增数据.DATA:" + JSONObject.toJSONString(VOList), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(VOList) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(VOList) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	/*@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		AudRejectOpinionVO entity = null;
		try {
			entity = new AudRejectOpinionVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			boolean success = this.audRejectOpinionService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}*/
	
	//********************私有方法********************//
	/**
	 * 获取参数信息
	 * @param request
	 * @return
	 * @throws BaseException
	 */
	private List<AudRejectOpinionVO> getRequestParam(HttpServletRequest request)throws BaseException{
		
		List<AudRejectOpinionVO> audRejectOpinionVOList = new ArrayList<AudRejectOpinionVO>();
		List<AudRejectOpinionPageVO> pageVOList = new ArrayList<AudRejectOpinionPageVO>();
		
		String projectId = request.getParameter("projectId");//项目ID
		String capPayId = request.getParameter("capPayId");//付款信息ID
		if(StringUtils.isEmpty(projectId) && StringUtils.isEmpty(capPayId)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "项目ID和付款信息ID至少有一个不为空.");
		}
		String proIntId = request.getParameter("proIntId");//流程ID
		String taskId = request.getParameter("taskId");//任务ID
		String taskDefKey = request.getParameter("taskDefKey");//任务定义KEY
		String taskNm = request.getParameter("taskNm");//任务定义名称
		String opinionTypeCd = request.getParameter("opinionTypeCd");//驳回意见类型
		String opinionDetailJSON = request.getParameter("opinionDetailJSON");//驳回意见JSON
		if(StringUtils.isEmpty(proIntId)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "流程ID不能为空");
		}
		if(StringUtils.isEmpty(taskId)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "任务ID不能为空");
		}
		if(StringUtils.isNotEmpty(opinionDetailJSON)){
			pageVOList = JSON.parseArray(opinionDetailJSON, AudRejectOpinionPageVO.class);
		}
		/*if(CollectionUtils.isEmpty(pageVOList)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "驳回意见不能为空");
		}*/

		//PgaeVOList -> VOList
		if(CollectionUtils.isNotEmpty(pageVOList)){
			audRejectOpinionVOList = AudRejOpnPageVOTransform.toVOList(pageVOList);
			for (AudRejectOpinionVO audRejectOpinionVO : audRejectOpinionVOList) {
				if (StringUtils.isNotEmpty(audRejectOpinionVO.getRemark()) && audRejectOpinionVO.getRemark().length() > 100) {
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "备注字段不能大于100个字符");
				}
				if(StringUtils.isNotEmpty(projectId)){
					audRejectOpinionVO.setProjectId(Long.valueOf(projectId));
				}
				if(StringUtils.isNotEmpty(capPayId)){
					audRejectOpinionVO.setCapPayId(Long.valueOf(capPayId));
				}
				audRejectOpinionVO.setProIntId(proIntId);
				audRejectOpinionVO.setTaskDefKey(taskDefKey);
				audRejectOpinionVO.setTaskNm(taskNm);
				audRejectOpinionVO.setTaskId(taskId);
				audRejectOpinionVO.setOpinionTypeCd(opinionTypeCd);
			}
		}
		
		return audRejectOpinionVOList;
	}
	
	/**
	 * 获取请求参数(
	 * @param request 请求
	 * @return 
	 */
	private List<AudRejectOpinionVO> getRequestParamForAdd(HttpServletRequest request)throws BaseException{
		List<AudRejectOpinionVO> audRejectOpinionVOList = this.getRequestParam(request);
		if(CollectionUtils.isNotEmpty(audRejectOpinionVOList)){
			for (AudRejectOpinionVO audRejectOpinionVO : audRejectOpinionVOList) {
				audRejectOpinionVO.setCrtTm(new Date());
				audRejectOpinionVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			}
		}
		return audRejectOpinionVOList;
	}
}

